package com.apeli.model;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;

@Component
public class InstantiationAwareBeanProcessor implements InstantiationAwareBeanPostProcessor, BeanPostProcessor, MergedBeanDefinitionPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("user")) {
            System.out.println("初始化后操作....postProcessAfterInitialization");
//            User user =(User)bean;
//            user.call();
//            return user;
        }
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("user")) {
            System.out.println("初始化前操作....postProcessBeforeInitialization");
//            User user =(User)bean;
//            user.call();
//            return user;
        }
       return null;
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanName.equals("user")) {
            System.out.println("实例化前操作....postProcessBeforeInstantiation");
//            return new User("apeli",10);
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (beanName.equals("user")) {
            System.out.println("实例化后...postProcessAfterInstantiation");
        }
        return false;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        if(beanName.equals("user")) {
            beanDefinition.setInitMethodName("init");
            System.out.println("合并Processor...postProcessMergedBeanDefinition");
        }
    }

    @Override
    public void resetBeanDefinition(String beanName) {

    }

}
